# -*- coding: utf-8 -*-..,
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp import tools

import pytz
import tzlocal
from tzlocal import get_localzone # $ pip install tzlocal

import openerp.addons.decimal_precision as dp
import time
import datetime
from datetime import timedelta
from datetime import datetime
from pickle import TRUE
import math
from ctypes.wintypes import DOUBLE
from lib2to3.pgen2.tokenize import Double
import operator
from itertools import count
import random
from sets import Set
from __builtin__ import map
import calendar
from calendar import monthrange


# ?????
#  only can be saving, afterchoosing "Active..."  => ???? 
#
# 
class crea8s_training1_demo_class(osv.osv):
    _name = "crea8s.training1.demo.class"
    _description = 'crea8s_training1.class-crea8s_t1'
    _columns = {
        'name': fields.char('Name', size=256),
        'name2': fields.char('Name2', size=256),
        'date': fields.date('Date'),
        'lang': fields.text('Language Text', size=256),
        'relation_id': fields.char('Relate_ID', size=256),
        'state': fields.selection([('draft', 'Draft'), ('confirmed', 'Confirmed')], 'StateAAA', readonly=False), #, required=True
#         'state': fields.text('Descaaa'),
        'active': fields.boolean('Active...'),
        
        'inventor_id': fields.many2one('res.partner','Inventor'),
        'vote_ids': fields.one2many('account.move.line', 'move_id','Votes'),
        # 'sponsor_ids': fields.many2many('res.partner','idea_sponsor_rel', 'idea_id','sponsor_id','Sponsors'),
        'tax_ids': fields.many2many('account.tax', 'account_account_tax_default_rel'
                                    ,'account_id', 'tax_id', 'Default Taxes'),
        'score': fields.float('Score',digits=(3,1)),
        'picture': fields.binary('Picture', filters='*.png,*.gif')
#         ,
# 'state': fields.selection([('draft','Draft'),
# ('confirmed','Confirmed')],'State',required=True,readonly=True)
    }
       
    strFormatTime = '%Y-%m-%d %H:%M:%S %Z'
    def act_helloword(self, cr, uid, ids, context={}):
       return self.write(cr, uid, ids, {'name': 'Hello word ! - PhongND said: "cr, uid, ids"'})
   
    def act_find_odd(self, cr, uid, ids, context={}):
# LIST:
#         aList = [1, 2, 3, 4]
# Dict:
#         aDict = {'host': 'earth'}
#         for key in aDict:
#             printkey, aDict[key]
        arrNum = [1, 2, 3, 4, 5, 17,14,16,18]
        arrRes = []
        strRes = ""
        valArr = {
                  "val1" : "1",
                  "val2" : "2",
                  }
        for key in arrNum:
            asd = key % 2
            if (asd == 1):
                arrRes.append(key)
#               number: strRes += key
                strRes = strRes + ";"+ str(key)
        
        print(arrRes)
        
        self.B2_2_TinhDienTichHinhChuNhat(cr, uid, ids, context)
        return self.write(cr, uid, ids, {'name': strRes})
  
    def B2_2_TinhDienTichHinhChuNhata(self, cr, uid, ids, context={}):
        strRes = 'asd'
        iHeigh = 3
        iWidth = 4
        iArea = iHeigh*iWidth
        
        print('B2_2_TinhDienTichHinhChuNhat = ' + str(iArea))
#                 return self.write(cr, uid, ids, {'name': strRes})
        self.TinhChuViDienTichHinhTron(cr, uid, ids, context)
        self.ThanhToanTienDien(cr, uid, ids, context)
        self.TinhCanhHuyenTamGiacVuong()
        self.TimSoLonHon()
        self.ChaoTheoGio()
        self.TinhDiemThiDaiHoc()
        self.GiaiPhuongTrinhBacNhat(4, 5)
        self.NhanDangTamGiac()
        self.TimThuTrongTuan()
        self.TinhNamAmLich(2012)
        self.TinhSoNgayTrongThang()
        self.TinhToanTrenDaySo()
        self.XuatBangCuuChuongMoRong()
        self.InSoNguyenTo()
        self.TestDoWhile()
        self.TimUCLNBCNT()
        self.GiaiPhuongTrinhBac2(0,4,5)
        self.ThayTheChuuoi()
        self.TimChuoi()
        self.tachchuoi()
        self.TinhTuoi(1988, 03, 27)
        self.TinhNamAmLich_2List(1988)
        print 'GetGoodsPrice_tuple: ' + str(self.GetGoodsPrice_tuple())
        self.SortPrice_ASC(self.GetGoodsPrice_tuple())
        self.SortPrice_DESC(self.GetGoodsPrice_tuple())
        print 'GetGoodsPrice_dictionary: ' + str(self.GetGoodsPrice_dict())
        self.SortPrice_ASC_dict(self.GetGoodsPrice_dict())
        self.SortCustomerCost(self.GetCustomer_dict())
        boFav = False
        print 'CalculateTotalPrice= '+ str(self.CalculateTotalPrice(self.GetGoodsPrice_dict(), boFav))
        arrThongTinHoa = self.CreateFlowerItem('f01','rose 03',14,1100)
        arrFlowerCode = ['f01', 'f02']
        arrFlowerName = ['flower 01', 'flower 02']
        arrQty = [1, 2]
        arrPrice = [1000, 2000]
        arrFlowerCart = self.TaoMangGioHoa(arrFlowerCode, arrFlowerName, arrQty, arrPrice)
        self.UpdateFlowerCart(arrFlowerCart, arrThongTinHoa)
        arrNumbers = self.TaoMangRandom(4)
        self.TaoMangRandom_TinhTong(arrNumbers)
        self.TaoMangRandom_TimMax(arrNumbers)
        self.TaoMangRandom_TimMin(arrNumbers)
        self.TaoMangRandom_TimKiem(arrNumbers, 3)
        strNumbers="1 4 5 6 7 4 9"
        self.TimKiemTrongChuoi(strNumbers, 4)
        self.TimKiemThayThe(arrNumbers, random.randint(0,9), random.randint(0,9))
        self.TimKiemThayThe_String(strNumbers, random.randint(0,9), random.randint(0,9))
        self.HoanVi(strNumbers)
        self.HoanVi2_Inverse(strNumbers)
        print '+ arrNumbers: ' + str(arrNumbers) 
        self.Test_PassByReference1(arrNumbers)
        print '+ after doing "Test_PassByReference1", arrNumbers: ' + str(arrNumbers)
        
        arrFirst = [1, 2, 3]
        arrSecond = [4, 5, 6, 3]
        self.array_merge(arrFirst, arrSecond)
        arrFirst = {'k1': 1, 'k2': 2}
        arrSecond = {'k3': 3, 'k4': 4, 'k2': 222}
        self.array_merge(arrFirst, arrSecond)
        #AAAAA: 
        #arrFirst = set([{'code': 'c01', 'name': 'name 01'}, {'code': 'c02', 'name': 'name 02'}]) # TypeError: unhashable type: 'dict'
        arrFirst = set([1, 2, 3])
        arrSecond = set([4, 5, 6, 3])
        self.array_merge(arrFirst, arrSecond)
        
        self.Test_SetInPython()
        self.Test_ListInPython()
        self.Test_DictionaryInPython()
        
        arrFirst = [1, 2, 3]
        arrSecond = [4, 5, 6]
        self.SapTang(arrFirst)
        
        str1 = '5 1 6 7 3'
        str2 = '8 2  6 9 3  '
        self.ProcessArray(strNumbers2 = str1, strNumbers1=str2)        
#         self.ProcessArray(str1, str2)        
        self.TinhNamAmLich(2012)
        self.ProcessDatetime()
        self.ProcessDatabasePostgre(cr, uid)
        strFirstDayOfAccountingPeriod = '2014-04-01'


#res: 
# + nuMoneyDischarge_week: 57.2
# + nuMoneyDischarge_year: 27; nuCountDaysoff:21
# + nuSalary_return: 715.8
        arrDaysOff = [{'date': '2014-04-01', 'right': 'no'}, {'date': '2014-04-06', 'right': 'no'}
  , {'date': '2014-04-02', 'right': 'yes'}, {'date': '2014-04-03', 'right': 'yes'}
  , {'date': '2014/05/07', 'right': 'no'}, {'date': '2014/05/05', 'right': 'no'}

  , {'date': '2014/04/10', 'right': 'no'}, {'date': '2014.04.11', 'right': 'no'}
  , {'date': '2014/04/12', 'right': 'no'}, {'date': '2014.04.13', 'right': 'no'}
  , {'date': '2014/04/14', 'right': 'no'}, {'date': '2014.04.15', 'right': 'no'}
  , {'date': '2014/04/16', 'right': 'no'}, {'date': '2014.04.17', 'right': 'no'}
  , {'date': '2014/04/18', 'right': 'no'}, {'date': '2014.04.19', 'right': 'no'}
  , {'date': '2014/04/20', 'right': 'no'}, {'date': '2014.04.21', 'right': 'yes'}
 
  , {'date': '2014.05.07', 'right': 'no'},  {'date': '2014-05-09', 'right': 'no'}
  , {'date': '2014.04.07', 'right': 'no'},  {'date': '2014-04-09', 'right': 'no'}
  , {'date': '2014.12.07', 'right': 'no'},  {'date': '2014-12-09', 'right': 'no'}
  ]     
        arrDiscountYear = {'value': 15, 'type': 'per'}
        nuSalaryMonthly = 800
        nuCurrentMonth = 5
        self.calSalaryMonthly(strFirstDayOfAccountingPeriod, arrDaysOff, arrDiscountYear, nuSalaryMonthly, nuCurrentMonth)
       
        self.getAccountMoveLines( cr, uid,'SCNJ/2014/005', context)
        
        
#         self.SortCustomerCost(self.GetGoodsPrice_dict())
        return True
   
    def TinhChuViDienTichHinhTron(self, cr, uid, ids, context):
        iRad = 5
        dPI = 3.14
        dCircleArea = iRad ** 2 * dPI
        
        print('dCircleArea = ' + str(dCircleArea))        
        return True
    def ThanhToanTienDien(self, cr, uid, ids, context):
        iOld = 12
        iNew = 14
        dPrice = 2.25
        dTotalMoney = (iNew - iOld) * dPrice
        print('ThanhToanTienDien = ' + str(dTotalMoney))   # dTotalMoney ===== float
        return True
    def TinhCanhHuyenTamGiacVuong(self):
        dA = 3
        dB = 4
        dC = math.sqrt(dA ** 2 + dB**2)
#         math.sqrt(-1)
        print('TinhCanhHuyenTamGiacVuong = ' + str(dC))
        return True
    def TimSoLonHon(self):
        dA = 3
        dB = 4
        dRes = 0
        if dA >= dB:
            dRes = dA
        else:
            dRes = dB
        print('TimSoLonHon = ' + str(dRes))
        return True
    def ChaoTheoGio(self):
        dCurrentTime = datetime.now() # datetime.today()
        print dCurrentTime
        dCurrentTime = 12
        strGreetingString = 'unknown'
        if dCurrentTime < 12:
            strGreetingString = 'Good moorning'
        elif (dCurrentTime >= 12 & dCurrentTime < 18):
            strGreetingString = 'Good afternoon'
        else:
            strGreetingString = 'Good night'
            
        print ('ChaoTheoGio = "' + strGreetingString +'"')
        return True
    def TinhDiemThiDaiHoc(self):
        dMark1 = 1
        dMark2 = 8
        dMark3 = 9
        dMarkStandard = 20
        dRes = "Chua biet"
        if (dMark1 <= 4 or dMark2 <= 4):
            dRes = 'Fail 1: <=4'
        elif (dMark1 + dMark2 + dMark3) < 20:
            dRes = 'Fail 2: <20'        
        else:
            dRes = 'success'
        
        
        
        
        print ('TinhDiemThiDaiHoc: ' + str(dRes))
        return True
    def GiaiPhuongTrinhBacNhat(self, dA, dB):
        dRes = 'unknown'
#         dA =0
#         dB = 1

        dC = float(0.0)
        if dA == 0:
            if dB == 0:
                dRes = 'PT vo so nghiem'
            else:
                dRes = 'Pt vo nghiem'
        else:
            dC = float(-dB)/float(dA)  
            dRes = 'Nghiem of PT: ' + str(dC)          
        print ('GiaiPhuongTrinhBacNhat: ' + str(dRes))
        return True
    
    def NhanDangTamGiac(self):        
        dRes = 'unknown'
        dA = 3
        dB = 4
        dC = 5
        
        if (dA + dB) > dC and (dA + dC) > dB and (dB + dC) > dA:
            dRes = 'Co the la 1 TAM GIAC'
            if (dA == dB) and (dB == dC):
                dRes = 'Tam giac DEU'
            elif (dA == dB or dA == dC or dB == dC) and (dA ** 2 + dB ** 2 == dC **2):
                dRes = 'Tam giac VUONG CAN'
            elif (dA ** 2 + dB ** 2 == dC **2):
                dRes = 'Tam giac VUONG'
        else:
            dRes = 'Khong phai la tam giac'
                
        print ('NhanDangTamGiac: ' + str(dRes))
        return True
        
    def TimThuTrongTuan(self):
        dRes = 'unknown'
#         dRes = datetime.datetime.now() # === datetime.now(); 
#         dRes = datetime.time(datetime.now()) #... datetime.today(); 
#         ??? dRes = datetime.now().strptime(start_date, "%Y-%m-%d")
#         dRes = datetime.now().strftime('%Y-%m-%d')
#         ??? dich ngay + 5ngay
#         ??? tim ngay cuoi cung of thang
        iDayOfWeek = datetime.today().weekday()
        if iDayOfWeek == 0:
            dRes = 'Monday'
        elif iDayOfWeek == 1:
            dRes = 'Teusday'
        elif iDayOfWeek == 2:
            dRes = 'Wednesday'
        elif iDayOfWeek == 3:
            dRes = 'Thursday'
        elif iDayOfWeek == 4:
            dRes = 'Friday'
        elif iDayOfWeek == 5:
            dRes = 'Saturday'
        elif iDayOfWeek == 6:
            dRes = 'Sunday'
        
        print ('TimThuTrongTuan: ' + str(dRes))
        return True
    
    def TinhNamAmLich(self, iYear):
        dRes = 'unknown'
#         iYear = 2014
        iSoDuCan = (iYear - 3) % 10
        strCan = 'unknown'
        strChi = 'unknown'
        
        if iSoDuCan == 0:
            strCan = 'Quy'
        elif iSoDuCan == 1:
            strCan = 'Giap'
        elif iSoDuCan == 2:
            strCan = 'At'
        elif iSoDuCan == 3:
            strCan = 'Binh'
        elif iSoDuCan == 4:
            strCan = 'Dinh'
        elif iSoDuCan == 5:
            strCan = 'Mau'
        elif iSoDuCan == 6:
            strCan = 'Ky'
        elif iSoDuCan == 7:
            strCan = 'Canh'
        elif iSoDuCan == 8:
            strCan = 'Tan'
        elif iSoDuCan == 9:
            strCan = 'Nham'
        elif iSoDuCan == 10:
            strCan = 'Quy'
        
        iSoDuChi = (iYear - 3) % 12
        
        if iSoDuChi == 0:
            strChi = 'Hoi'
        elif iSoDuChi == 1:
            strChi = 'Ty (chuột)'
        elif iSoDuChi == 2:
            strChi = 'Suu'
        elif iSoDuChi == 3:
            strChi = 'Dan'
        elif iSoDuChi == 4:
            strChi = 'Mao'
        elif iSoDuChi == 5:
            strChi = 'Thin (rồng)'
        elif iSoDuChi == 6:
            strChi = 'Ty (rắn)'
        elif iSoDuChi == 7:
            strChi = 'Ngo (ngựa)'
        elif iSoDuChi == 8:
            strChi = 'Mui (dê)'
        elif iSoDuChi == 9:
            strChi = 'Than (khỉ)'
        elif iSoDuChi == 10:
            strChi = 'Dau (hổ)'
        elif iSoDuChi == 11:
            strChi = 'Tuat (chó)'
        dRes = 'Nam '  + str(iYear) + ' la nam ' + strCan + ' ' + strChi
        print('TinhNamAmLich: ' + str(dRes))
        return True
    
    def TinhSoNgayTrongThang(self):
        dRes = 'unknown'
        dYear = 2014
        dMonth = 2
        dicDays = {1 : 31, 3: 31, 4: 30, 5: 51, 6: 30, 7: 31
                   , 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
        iCountDays = 0
        if dMonth == 2:
            if dYear % 4 == 0:
                iCountDays = 29
            else:
                iCountDays = 28
        else:
            iCountDays = dicDays[dMonth]
            
        dRes = 'The month ' + str(dMonth) + 'th of ' + str(dYear) + ' has '+ str(iCountDays) + ' days'
        print('TinhSoNgayTrongThang: ' + str(dRes))
        return True
    
    def TinhToanTrenDaySo(self):
        dRes = 'unknown'
        dStart = 1
        dStop = 10
        dStep = 3
        dSum = 0
        dMul = 1
        iCountOdd = 0
        iCountEven = 0
        for i in xrange(dStart, dStop+1, dStep):
            if i % 2 == 0:
                iCountEven += 1
            else:
                iCountOdd += 1
            
            dSum += i
            dMul *= i
        
        dRes = 'count_odd= ' + str(iCountOdd) + '; count_even= ' + str(iCountEven) + '; sum= ' + str(dSum) + '; mul= ' + str(dMul)
        print('TinhToanTrenDaySo: ' + str(dRes))
        return True
    
    def XuatBangCuuChuongMoRong(self):
        dRes = 'unknown'
        dStart = 4
        dStop = 5
        dStep = 1
        print('XuatBangCuuChuongMoRong: ' + str(dRes))
        for i in xrange(dStart, dStop+1, dStep):
            strTemp = '+ CuuChuong ' + str(i) + ': '
            for j in xrange(1, 11, 1):
                strTemp += str(i) + ' x ' + str(j) + ' = ' + str(i*j) + '; '
            print(strTemp)
        
        
        return True
    
    def KiemTraSoNguyenTo(self, dNum):
        for i in xrange (2, dNum, 1):
            if dNum % i == 0:
                return False 
                
        return True
    def InSoNguyenTo(self):
        dNum = 7
        dRes = 'unknown'
        if dNum < 2:
            dRes = ' ko co so nguyen to '
        else:
            dRes = ' Day so nguyen to=== '
            for i in xrange(2, dNum+1, 1):
                if self.KiemTraSoNguyenTo(i) == True:
                    dRes += str(i) + '; '
                
        print('InSoNguyenTo: ' + dRes)
        return True
    
    def TestDoWhile(self):
        dRes = ''
        iNum = 3
        while iNum >0:
            dRes += str(iNum) + '; '
            iNum -= 1
        
        
        print('TestDoWhile: ' + dRes)
        return True
    def TimUCLNBCNT(self):
        dRes = 'unknown'
        dA = 6
        dB = 12
        dStart = 1
        dUCLN = 1
        dSmaller = dB if dA >= dB else dA  #  for python2.5 and newer,
        while dStart <= dSmaller:
            if dA % dStart == 0 and dB % dStart == 0:
                dUCLN = dStart
            dStart += 1
        dRes = 'UCLN= ' + str(dUCLN)
        
        dLarger = dA if dA >= dB else dA
        dStart = dLarger
        dBCNN = dA * dB / dUCLN 
        dRes += '; BCNN= ' + str(dBCNN)
        
        print ('TimUCLNBCNT: ' + dRes)
        return True
    
    def GiaiPhuongTrinhBac2(self, dA, dB, dC):
#         dA = 0
#         dB = 4
#         dC = 5
        dRes = 'unknown'
        dNghiem = 'unknown'
        if dA == 0:
            dNghiem = self.GiaiPhuongTrinhBacNhat(dB, dC)
        
        
        
        print('GiaiPhuongTrinhBac2: ' + dRes)
        return True
    
    def ThayTheChuuoi(self):
        strText = 'One two three two four two'
        strFind = 'two'
        strReplaceBy = 'asd'
        dRes = 'unknown'
        
        print ('ThayTheChuuoi: ' + dRes)
        dRes = '+ origin= ' + strText
        print(dRes)
        
        strR1 = strText.replace(strFind, strReplaceBy)
        print ('+ replaced1= ' + strR1)
        strR2 = strText.replace(strFind, strReplaceBy, 1)
        print ('+ replaced2= ' + strR2)
        
        str = "this is string example....wow!!! this is really string"
        print str.replace("is", "was")
        print str.replace("is", "was", 3)

        return True
    
    def TimChuoi(self):
        strText = 'On ID day of this year 2014 (1/5), we relax at home, play badminton, eat mango, ride bicycle, etc... This weekend, we make campaign to DongNai province.'
        strFind = 'play'
        iPos = strText.find(strFind)
        print 'TimChuoi:'
        print '+ Text: ' + strText
        print '+ The string \'' + strFind + '\' has been found at the position ' + str(iPos) + 'th of above text.'
        
        return True
    
    def tachchuoi(self):
        print 'tachchuoi: '
        # this function do as well as the explode() in php
        strText = 'Nguyen Duy Phong'
        arrText = strText.split(' ')
        
        dRes = 'Ho= ' + arrText[0] + '; dem= ' + arrText[1] + '; ten= ' + arrText[2]
        
        print '+ after splitting: ' + dRes
        dRes = '.'.join(arrText)
        print '+ after joining: '  + dRes
        
        return True
    
    def TinhTuoi(self, dYear, dMonth, dDay):
        strDate = str(dYear) +'-' + str(dMonth) + '-' + str(dDay)
        dtBirthday = datetime.strptime(strDate, '%Y-%m-%d')
        dtBirthday = dtBirthday.replace(tzinfo = get_localzone())
        
        
        # METHOD 1: Hardcode zones:
#         utc_zone = tz.gettz('UTC')
#         local_zone = tz.gettz('America/Chicago')
        # METHOD 2: Auto-detect zones:
#         utc_zone = tz.tzutc()
#         local_zone = tz.tzlocal()
        # ===== add more few days                                               
        current_date = datetime.utcnow()
        tdDelta = timedelta(days=3) # no, error: datetime.timedelta(days=3)
        curDateAdd3 = current_date + tdDelta
        strFM = '%Y-%m-%d %H:%M:%S %Z'
        print '+ curDateAdd3(DEFAULT_SERVER_DATE_FORMAT)= ' + curDateAdd3.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
        print '+ curDateAdd3= ' + curDateAdd3.strftime(strFM)
        # ===== utcnow                                                              
        strTemp = datetime.utcnow()
        print '+ utcnow= ' + str(strTemp.strftime("%Y-%m-%d %H:%M:%S"))
        # Convert time string to datetime
        local_time = datetime.strptime("2008-09-17 14:02:00", '%Y-%m-%d %H:%M:%S')
        
        # ===== timezone                                   
#         current_date = datetime.utcnow()
#         tz = get_localzone()
#         local_dt = tz.localize(current_date, is_dst=None)
#         print local_dt
        # ===== timezone2 
        current_date = datetime.utcnow()
        utc_tz =  pytz.timezone('UTC')
        utc_dt = utc_tz.localize(current_date, is_dst=False)
        # =====
        utc_dt2 = pytz.utc.localize(current_date)
        print '+ utc_dt2= ' + utc_dt2.strftime(strFM) # ??? strftime() doesn't officially support %z.
        # ===== 
        local_dt = utc_tz.localize(datetime(2014, 03, 27, 12, 0, 0, 0), is_dst=None)
        print '+ utc_dt3= ' + local_dt.strftime('%Y-%m-%d %H:%M:%S %z')
        

        local_dt = datetime.now(pytz.timezone("America/New_York")) # 06:02:51 EDT
        print '+ utc_dt4= ' + local_dt.strftime(strFM)
        
        # =====         
        local_dt = datetime.now(pytz.timezone("UTC"))
        utc_tz =  pytz.timezone('America/New_York')
        local_dt = local_dt.replace( tzinfo=utc_tz ) # ???: WRONG? 10:00:00 UTC => 10:00:00 EST
        d1 = local_dt.strftime(strFM)
#         d2 = datetime.datetime.strptime(d_string, strFM)
        print '+ utc_dt5= ' +  d1
        
        # =====         
        local_dt = datetime.utcnow()
#         d2 = datetime.datetime.strptime(d_string, strFM)
        print '+ utc_dt6= ' +  local_dt.strftime(strFM) + ' (utcnow)'
        
        # =====         
        local_dt = datetime.now(get_localzone())
#         d2 = datetime.datetime.strptime(d_string, strFM)
        print '+ utc_dt7= ' +  local_dt.strftime(strFM) + ' (get_localzone)'
        
        # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        dtCurrentDate = datetime.now(get_localzone())
        dtBirthday_currYear = datetime.strptime(str(dtCurrentDate.year) + '-' + str(dtBirthday.month) + '-' + str(dtBirthday.day), '%Y-%m-%d')
        dtBirthday_currYear = dtBirthday_currYear.replace(tzinfo = get_localzone())
        
        if dtBirthday_currYear < dtCurrentDate:
            dtBirthday_currYear = datetime.strptime(str(dtCurrentDate.year+1) + '-' + str(dtBirthday.month) + '-' + str(dtBirthday.day), '%Y-%m-%d')
        
        #bat buoc fai chuyen tzinfo ; neu ko: ...TypeError: can't subtract offset-naive and offset-aware datetimes
        dtBirthday_currYear = dtBirthday_currYear.replace(tzinfo = get_localzone())
        
        print 'TinhTuoi: ' + str(dtBirthday)
        deltaDaysLeft = dtBirthday_currYear - dtCurrentDate
        print '+ dtCurrentDate = ' + dtCurrentDate.strftime(self.strFormatTime)
        print '+ It\'s ' + str(deltaDaysLeft.days) + ' days left for getting ur bd. '
        
        return True
    
    def TinhNamAmLich_2List(self, iYear):
        arrCan = ['Quy', 'Giap', 'At', 'Binh', 'Dinh', 'Mau', 'Ky', 'Canh', 'Tan', 'Nham']
        arrChi = ['Hoi', 'Ty', 'Suu', 'Dan', 'Meo', 'Thin', 'Ty', 'Ngo', 'Mui', 'Than', 'Dau', 'Tuat']
        strCan = arrCan[(iYear-3)%10]
        strChi = arrChi[(iYear-3)%12]
        
        print 'TinhNamAmLich_2List: ' + str(iYear) + " (" + strCan + ' ' + strChi +')'
        return True
    
    def GetGoodsPrice_tuple(self):
        dicGoodsPrice = {'g1': 15, 'g2': 12, 'g3': 21, 'g4': 18}
#         dicGoodsPrice.iteritems() #D.iteritems() -> an iterator over the (key, value) items of D
#         dicGoodsPrice.iterkeys()
        dictTmp = self.GetGoodsPrice_dict()
        dicGoodsPrice2 = {}        
#         loop a dictionary: for item in dicGoodsPrice2.keys():
        for index, item in enumerate(dictTmp): # loop a list.
            dicGoodsPrice2[item['goodscode']] = item['price']            
        return dicGoodsPrice2
    
    def SortPrice_ASC(self, dicGoodsPrice):
        
        sorted_x = sorted(dicGoodsPrice.iteritems(), key=operator.itemgetter(1))
        print '+ SortPrice_ASC: ' + str(sorted_x)
        print '+ SortPrice_ASC-goodscode: ' + str(dicGoodsPrice.keys())
        return True
    
    def SortPrice_DESC(self, dicGoodsPrice):        
        sorted_x = sorted(dicGoodsPrice.iteritems(), key=operator.itemgetter(1), reverse=True)        
        print '+ SortPrice_DESC: ' + str(sorted_x)
        return True
    
#         dicGoodsPrice.iteritems() #D.iteritems() -> an iterator over the (key, value) items of D
#         dicGoodsPrice.iterkeys()

    def GetGoodsPrice_dict(self):
        dicGoodsPrice = [{'goodscode': 'g2', 'price': 80, 'qty': 1}, {'goodscode': 'g1', 'price': 55, 'qty': 1}
                         , {'goodscode': 'g3', 'price': 70, 'qty': 1}, {'goodscode': 'g4', 'price': 50, 'qty': 42}]
#         enumerate(dicGoodsPrice)
        return dicGoodsPrice
    def SortPrice_ASC_dict(self, dicGoodsPrice):
        
        sorted_x = sorted(dicGoodsPrice, key=operator.itemgetter('price'))
        print '+ SortPrice_ASC_dict: ' + str(sorted_x)
        
        return True
    def GetCustomer_dict(self):
        dicCust = [{'code': 'cu01', 'add': 'Q8', 'cost': 20, 'EffectiveDistanceFromQ8': 100}
                   ,{'code': 'cu02', 'add': 'Q2', 'cost': 10, 'EffectiveDistanceFromQ8': 70}
                   ,{'code': 'cu03', 'add': 'Q1', 'cost': 15, 'EffectiveDistanceFromQ8': 60}
                   ,{'code': 'cu04', 'add': 'Q5', 'cost': 20, 'EffectiveDistanceFromQ8': 90}
                   ,{'code': 'cu05', 'add': 'Q6', 'cost': 10, 'EffectiveDistanceFromQ8': 80}                   
                   ]
        
        return dicCust
    
    def SortCustomerCost(self, dicCust):
        
        sorted_x = sorted(dicCust, key=operator.itemgetter('cost', 'EffectiveDistanceFromQ8'), reverse=True)        
        print 'SortCustomerCost: ' + str(sorted_x)        
        return True
    def CalculateTotalPrice(self, arrGoods, boFavouriteCust):
        totalPrice = float(0) 
#         arrGoods = self.GetGoodsPrice_dict() #return TYPE: DICTIONARY
        fDiscount200k = float(0) 
        fDiscount20items = float(0) 
        fDiscount500k = float(0) 
        
        for index, item in enumerate(arrGoods): # loop a list.
            item['price_on_line'] = item['qty'] * item['price']
            totalPrice += item['price_on_line'] 
    
        if boFavouriteCust == True:
            if totalPrice >= 500:
                fDiscount200 = 0
                fDiscount500 = totalPrice * 0.2
            elif totalPrice >= 200:
                fDiscount200 = totalPrice * 0.05
                fDiscount500 = 0
                
            for index, item in enumerate(arrGoods): # loop a list.
#                 dicGoodsPrice2[item['goodscode']] = item['price']
                countGoods = item['qty']
                if countGoods >= 20:
                    fDiscount20items += (countGoods/20) * 10
        else:
            if totalPrice >= 200:
                fDiscount200 = totalPrice * 0.05
                fDiscount500 = 0
                
        totalPrice = totalPrice - fDiscount200 - fDiscount500 - fDiscount20items
        return totalPrice
    
    def CreateFlowerItem(self, code, name, qty, price):
        return {'code': code, 'name': name, 'qty': qty,'price': price, 'misc01': '', 'misc02': '', 'misc03': ''}
    
    def TaoMangGioHoa(self, arrFlowerCode, arrFlowerName, arrQty, arrPrice):
        arrGioHoa = []
        for i, flowerCode in enumerate(arrFlowerCode):
            arrFLower = self.CreateFlowerItem(flowerCode, arrFlowerName[i], arrQty[i], arrPrice[i])
            arrGioHoa.append(arrFLower)
        
        
        
        print 'TaoMangGioHoa:' + str(arrGioHoa)
        return arrGioHoa
    def TimHoa(self):
        
        print 'TimHoa:'
        return True
    def UpdateFlowerCart(self, arrGioHoa, arrFlower):
        
        bFound = False
        arrFlowerOK = {}
        for i, flowerTMP in enumerate(arrGioHoa):
            if flowerTMP['code'] == arrFlower['code']:
                bFound = True
                arrFlowerOK = flowerTMP
        if bFound == True:
            arrFlowerOK['qty'] += arrFlower['qty']            
        else:
            arrFlowerOK = arrFlower
            arrGioHoa.append(arrFlower)
        
              
        print 'UpdateFlowerCart:' + str(arrFlowerOK['code']) + ' qty='+ str(arrFlowerOK['qty'])        
        print 'UpdateFlowerCart-arrGioHoa:' + str(arrGioHoa)
        
        return True
    
    def TaoMangRandom(self, iQty):
        arrNumbers = []
        for i in xrange(0, iQty, 1):
            arrNumbers.append(random.randint(0,9))
        # generate random number from 1~9: randrange(10)
        # shorten "loop sentence" : x=[randint(0,10) for p in range(0,10)]

        
        print 'TaoMangRandom: ' + str(arrNumbers)
        return arrNumbers 
    def TaoMangRandom_TinhTong(self, arrNumbers):
        iSum = 0
        for value in arrNumbers:
            iSum += value    
            
        print 'TaoMangRandom_TinhTong: ' + str(iSum)
        return True
    def TaoMangRandom_TimMax(self, arrNumbers):
        iMax = 0
        for i, value in enumerate(arrNumbers):
            if value > iMax:
                iMax = value
            
        print 'TaoMangRandom_TimMax: ' + str(iMax)
        return True
    
    def TaoMangRandom_TimMin(self, arrNumbers):
        iMin = 9
        for i, value in enumerate(arrNumbers):
            if value < iMin:
                iMin = value
            
        print 'TaoMangRandom_TimMin: ' + str(iMin)
        return True
    
    def TaoMangRandom_TimKiem(self, arrNumbers, iFindingValue):
        bFound = False
        iPos = ""
        for i, value in enumerate(arrNumbers):
            if int(value) == int(iFindingValue):
                bFound = True
                iPos += str(i + 1) + ", "
        if bFound == True:
            print 'TaoMangRandom_TimKiem: ' + 'The number "' + str(iFindingValue) + '" has been found at the position(s) ' + str(iPos) 
        else:
            print 'TaoMangRandom_TimKiem: ' + 'The number "' + str(iFindingValue) + '" has NOT been found.'  
        return True
    def TimKiemTrongChuoi(self, strNumbers, iFindingValue):
        arrNumbers = strNumbers.split(' ')
        print 'TimKiemTrongChuoi: ' + strNumbers 
        print '+ arrNumbers: ' + str(arrNumbers)
        self.TaoMangRandom_TimKiem(arrNumbers, iFindingValue)
        
        return True
        
    def TimKiemThayThe(self, arrNumbers, iOld, iNew):
        
                
        print 'TimKiemThayThe:'                
                
        print '+ old numbers: ' + str(arrNumbers)                
        print '+ replace : ' + str(iOld) + ' by ' + str(iNew) 
        
        for i,value in enumerate(arrNumbers) :
            if int(value) == int(iOld):
                arrNumbers[i] = iNew
                
        print '+ NEW numbers: ' + str(arrNumbers)
        return arrNumbers
    def TimKiemThayThe_String(self, strNumbers, iOld, iNew):
        print 'TimKiemThayThe_String: ...'
        print '+ strNumbers: ' + strNumbers  
        arrNumbers = strNumbers.split(' ')
        arrNumbers_changed = self.TimKiemThayThe(arrNumbers, iOld, iNew)
        
        print '+ arrNumbers_changed: ' + str(arrNumbers_changed) 
        
        # convert array INT to string array
        for i, value in enumerate(arrNumbers_changed):
            arrNumbers_changed[i] = str(value)
        print '+ arrNumbers_changed (join): ' + '; '.join(arrNumbers_changed) 
                
        
        return True
    def HoanVi(self, strPermute):
        
        print 'HoanVi: '
        print '+ old: ' + strPermute
        arrPermute = strPermute.split(' ')
        strTemp = arrPermute[0]
        arrPermute[0] = arrPermute[1]
        arrPermute[1] = strTemp
        strPermute = '; '.join(arrPermute)
        print '+ new: ' + strPermute
        
        return True
    
    
    def HoanVi2_Inverse(self, strInverse):
        
        print 'HoanVi2_Inverse: '
        print '+ old: ' + strInverse
        arrInverse = strInverse.split(' ')
        strTemp = arrInverse[0]
        arrInverse_new = []
#         nonono: for i, value in reversed(arrInverse):
        # m1
#         for value in arrInverse[::-1]: 
#             arrInverse_new.append(value)
        
        # m2
        for i, value in reversed(list(enumerate(arrInverse))):
            arrInverse_new.append(value)
        
        strInverse = '; '.join(arrInverse_new)
        print '+ new: ' + strInverse
        
        arrInverse_New222 = arrInverse[::-1]
        print '+ arrInverse_New222: ' + str(arrInverse_New222)
        
        return True
    
    def Test_PassByReference1(self, arrInput):
        print 'Test_PassByReference1: '
        print '+ got: ' + str(arrInput)
        # arrInput.append (123)
        arrInput = [1 , 2, 3]
        arrInput.append (123)
        print '+ set to: ' + str(arrInput)
                
        return True
    
#     def HoanVi3_Reference(self, arrNumber1, arrNumber2):
#         temp = arrNumber1[0]        
#         return True
    
    def array_merge(self, first_array , second_array ):
        print 'array_merge: in python'
        if isinstance( first_array , list ) and isinstance( second_array , list ):
            print '+ merge LIST into arrRe'
            arrRe = first_array + second_array
            print '+ arrRe: ' + str(arrRe)
            print '+ second_array(tuple): ' + str(tuple(second_array))
            print '+ second_array(SET!!): ' + str(set(tuple(second_array)))
            print '+ second_array(SET22): ' + str(set((second_array)))
            
            if isinstance( first_array , list ):
#                 first_array2 = set(list(first_array)) 
#                 second_array2 =  set(second_array)
#                 print '+ second_array2: ' + str(second_array2)
                arrRe = Set(first_array) | Set(second_array)
                print '+ arrRe-2(SET): ' + str(arrRe)
        elif isinstance( first_array , dict ) and isinstance( second_array , dict ):
            print '+ merge DICT into arrRe'
            arrRe = dict( list( first_array.items() ) + list( second_array.items() ) )
            print '+ arrRe: ' + str(arrRe)
        elif isinstance( first_array , set ) and isinstance( second_array , set ):
            print '+ merge SET into arrRe'
            arrRe = first_array.union( second_array )
            print '+ arrRe: ' + str(arrRe)
            arrRe = set(first_array)   | set(second_array)
            print '+ arrRe-2: ' + str(arrRe)
        
        return True
    
    def Test_SetInPython(self):
        engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
        programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
        managers = Set(['Jane', 'Jack', 'Susan', 'Zack'])
        
        print 'Test_SetInPython: '
        setUnion = engineers | programmers | managers
        print '+ union set: ' + str(setUnion)
#         setUnion = engineers + programmers + managers
#         print '+ union set(2+++): ' + str(setUnion)
        setIntersection = programmers & managers
        print '+ inter set(1): ' + str(setIntersection)
        setIntersection = programmers.intersection(managers)
        print '+ inter set(2): ' + str(setIntersection)
        setDiff = managers - programmers
        print '+ diff set: ' + str(setDiff)
        setUpdated = engineers.update(programmers)
        print '+ updated set(setUpdated): ' + str(setUpdated)
        print '+ updated set(engineers): ' + str(engineers)
        
        return True
    
    def Test_ListInPython(self):
        engineers = ['John', 'Jane', 'Jack', 'Janice']
        programmers = ['Jack', 'Sam', 'Susan', 'Janice']
        managers = ['Jane', 'Jack', 'Susan', 'Zack']
        
        print 'Test_ListInPython: '
#         ListUnion = engineers | programmers | managers
        ListUnion = engineers + programmers + managers
        print '+ union List: ' + str(ListUnion)
        
        ListUnion = list(set(engineers + programmers + managers))
        print '+ union List-2(SET): ' + str(ListUnion)
#         ListIntersection = programmers & managers
        ListIntersection = Set(programmers) & Set(managers)
        print '+ inter List: ' + str(ListIntersection)
        ListDiff = Set(managers) - Set(programmers)
        print '+ diff List: ' + str(ListDiff)
#         ListUpdated = engineers.update(programmers)
        print '+ updated List: NONONO'
        
        return True
    
    def Test_DictionaryInPython(self):
        
        engineers = {'key01': 'John', 'key02': 'Jane', 'key03': 'Jack', 'key04': 'Janice'}
        programmers = {'key01': 'Jack', 'key02': 'Sam', 'key03': 'Susan', 'key05': 'Janice'}
        managers = {'key01': 'Jane', 'key02': 'Jack', 'key03': 'Susan', 'key04': 'Zack'}
        
        print 'Test_DictInPython: '
#         DictUnion = engineers | programmers | managers
        DictUnion = dict(list(engineers.items()) + list(programmers.items()) + list(managers.items()))
        print '+ union Dict: ' + str(DictUnion) # okokok: cool!!!
        DictUnion = dict(sum(map(lambda dct: list(dct.items()), [engineers, programmers, managers]), [])) # *dicts ===  [engineers, programmers, managers]
        print '+ union Dict-2(sum(map(lambda ...): ' + str(DictUnion) # okokok: cool!!!
        
#         DictIntersection = programmers & managers
        DictIntersection = Set(programmers.keys()) & Set(managers.keys())
        print '+ inter Dict(for KEYs): ' + str(DictIntersection)
        DictDiff = Set(managers.keys()) - Set(programmers.keys())
        print '+ diff Dict(for KEYs): ' + str(DictDiff)

        print '+ updated Dict(nonono): ' 
        
        return True
    def SapTang(self, arrNumbers):
        
        print 'SapTang: '
        for i,iNum in enumerate(arrNumbers):
            arrNumbers[i] = 1
        print '+ arrNumbers: ' + str(arrNumbers)
        print [l for l in arrNumbers]
        return True
    
    
    #2 day so:
    #+ (string): 5 1 6 7 3 
    #+ (string): 8 2 6 9 3
    # => turn into: ASC, DESC
    # => merge
    # => diff: 1side; 2side
    # =>  asd
    def ProcessArray(self, strNumbers1 = '', strNumbers2 = ''):
        arrNumbers1 = strNumbers1.split(' ')
        arrNumbers2 = strNumbers2.split(' ')
        print 'ProcessArray:...arrNumbers1 => ' + str(arrNumbers1) + ', arrNumbers2 => ' + str(arrNumbers2)
        print '+ union ' + str(arrNumbers1 + arrNumbers2)
        print '+ union (distinct) ' + str(set(arrNumbers1).union(set(arrNumbers2)))
        
        
        return True
    
    def ProcessDatetime(self):
        
        
        print 'ProcessDatetime: '
        
        strFM = '%A %B %d %Y %H:%M:%S' # Tuesday June 17 2014 11:30:59   #???: dCurrentTime-2: �Ηj�� 6�� 17 2014 11:30:23
        dCurrentTime = datetime.now(get_localzone())
        print '+ dCurrentTime-2: ' + dCurrentTime.strftime(strFM) #???: dCurrentTime-2: �Ηj�� 6�� 17 2014 11:30:23
            
        strFM = '%Y-%m-%d %H:%M:%S %Z'
        dCurrentTime = datetime.now(get_localzone())
        print '+ dCurrentTime: ' + dCurrentTime.strftime(strFM)
        
        arrWeekDay = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
        iWeekDay = dCurrentTime.weekday()
        print '+ day of week: ' + str(iWeekDay) + ' isaa '+ str(arrWeekDay[iWeekDay])
        print '+ y/m/d: ' + str(dCurrentTime.year) + '/'+ str(dCurrentTime.month) + '/' + str(dCurrentTime.day)
        #monthrange: weekday of 1st &&& count days in month
        setMonthRange = monthrange(dCurrentTime.year, dCurrentTime.month)
        print '+ monthrange: ' + str(setMonthRange) 
        print '+ monthrange: weekday of 1st= ' + str(list(setMonthRange)[0]) + '; count= ' +str(list(setMonthRange)[1])  
       
       
       
       
        local_dt = datetime.now(pytz.timezone("America/New_York")) # 06:02:51 EDT
        print '+ utc_dt1 = ' + local_dt.strftime(strFM) + '(America/New_York)'
        
        # =====         
        local_dt = datetime.now(pytz.timezone("UTC"))
        print '+ utc_dt2.1= ' +  local_dt.strftime(strFM)   + '(UTC)'
        local_dt = datetime.now(pytz.timezone("UTC"))
        utc_tz =  pytz.timezone('America/New_York')
        local_dt = local_dt.replace( tzinfo=utc_tz ) # ???: WRONG? 10:00:00 UTC => 10:00:00 EST
#         d2 = datetime.datetime.strptime(d_string, strFM)
        print '+ utc_dt2.2= ' +  local_dt.strftime(strFM)   + '(America/New_York....replaced tzinfo=)'
       
        local_dt =  datetime.now(pytz.timezone('Asia/Tokyo')) 
        print '+ utc_dt3= ' + local_dt.strftime(strFM)  + '(Asia/Tokyo)'
        local_dt = datetime.now(pytz.timezone("UTC"))
        utc_tz_jp =  pytz.timezone('Asia/Tokyo')
        local_dt = local_dt.replace( tzinfo=utc_tz_jp ) #
        print '+ utc_dt4= ' +  local_dt.strftime(strFM)  + '(Asia/Tokyo....replaced tzinfo=)'
        
        
        


        
        return True
    
    
    def process_date_title(self, date_or):
        temp = datetime(int(date_or[:4]), int(date_or[5:7]), int(date_or[8:10]), int(date_or[11:13]), int(date_or[14:16]), int(date_or[17:19]))
#         temp += timedelta(hours=7)
        result = time.strftime('%a %b %d %Y %H:%M:%S',time.strptime(str(temp), '%Y-%m-%d %H:%M:%S'))
        
        return result + "-from 'prac...py'"

    def process_date_title2(self, date_or):
        temp = datetime(int(date_or[:4]), int(date_or[5:7]), int(date_or[8:10]), int(date_or[11:13]), int(date_or[14:16]), int(date_or[17:19]))
#         temp += timedelta(hours=7)
        result = time.strftime('%d-%m-%Y %H:%M:%S',time.strptime(str(temp), '%Y-%m-%d %H:%M:%S'))
        
        return result
    
    
    def ProcessDatabasePostgre(self,cr, uid):
        
        print 'ProcessDatabasePostgre: '
        cr.execute('select * from res_users')
        print 'ỗ ễ....' + str(cr.fetchall())
        
        
        print self.pool.get('res.users').search(cr, uid, [('id', '!=', 34)], order='id DESC')

# , '!', ('name', 'ilike', 'spam'),]
        
        
        return True
    def them_ngay(self,  cr, uid, ids, date_time, name):
        value = ''
        if date_time:
            if name:
                value = name + ' , ' + str(date_time)
            else:
                value = str(date_time)
        return {'value': {'name': value}}
    
    
    def calSalaryMonthly(self, strFirstDayOfAccountingPeriod, arrDaysOff, arrDiscountYear, nuSalaryMonthly, nuCurrentMonth):
        """calculate salary monthly of a employee...
        :author: phongnd
        :param str strFirstDayOfAccountingPeriod: yyyy/mm/dd or yyyy-mm-dd
        :param list arrDaysOff: 
        :param dict arrDiscountYear:  {'value': 15, 'type': 'per' OR 'mon'}
        :param number nuSalaryMonthly:  
        """
        arrDischargePerDay_YES = [0, 0.2, 0.4, 0.6, 0.8]
        arrDischargePerDay_NO = [0, 1, 2.2, 3.3, 4.4]
        
        arrYMD = strFirstDayOfAccountingPeriod.split('/')
        if len(arrYMD) < 3:
            arrYMD = strFirstDayOfAccountingPeriod.split('-')
        
        dFirstDate = datetime.strptime(arrYMD[0] + '-' + arrYMD[1] + '-'+ arrYMD[2], "%Y-%m-%d")
#         dFirstDate = dFirstDate.replace(tzinfo= pytz.timezone("America/New_York")) #..EST
        dFirstDate = dFirstDate.replace(tzinfo= get_localzone()) #.. BMT
        
#         dSalaryPerDay = nuSalaryMonthly / 30
        dSalaryPerDay = self.calAverageSalaryPerday(nuSalaryMonthly, dFirstDate.year, nuCurrentMonth)
        
        # convert
        arrDaysOff_datime = self.convertDatetimeFromArrayString(arrDaysOff)
                
        #vi pham so ngay nghi / tuan
        dictWeek_Daysoff = self.findOutDaysoffGroupByWeek(dFirstDate, arrDaysOff_datime, nuCurrentMonth)
        strTmp = ''
        nuMoneyDischarge_week = 0
        for key, value in dictWeek_Daysoff.items():
            nuRightYes = 0
            nuRightNo = 0
            for dayoff in value:
                if dayoff['right'] == 'yes':
                    nuRightYes += 1
                else:
                    nuRightNo += 1
            
            nuOverYes = nuRightYes - 1
            nuOverNo = nuRightNo - 1
            if nuOverYes > 4: nuOverYes = 4
            if nuOverNo > 4: nuOverNo = 4
            
            if nuOverYes > 0:
                nuMoneyDischarge_week += arrDischargePerDay_YES[nuOverYes] * dSalaryPerDay
            if nuOverNo > 0:
                nuMoneyDischarge_week += arrDischargePerDay_NO[nuOverNo] * dSalaryPerDay
#             if nuExtra > 0:
#                 nuMoneyDischarge_week = nuExtra *  
        
         
        #vi pham so ngay nghi: dau nam (KE TOAN) =>thang tinh luong
        dictWeek_Daysoff = self.findOutDaysoffGroupByWeek(dFirstDate, arrDaysOff_datime, 0)        
        nuMoneyDischarge_year = 0
        nuCountDaysoff = 0  
        nuMaxDaysoff = 14
        for key, value in dictWeek_Daysoff.items():
            for dayoff in value:
                if dayoff['date'].month <= nuCurrentMonth: #chi xet nuCurrentMonth ve truoc.
                    nuCountDaysoff += 1
        
        if nuCountDaysoff > nuMaxDaysoff:
            if arrDiscountYear['type'] == 'per':
                nuMoneyDischarge_year += dSalaryPerDay * (nuCountDaysoff - nuMaxDaysoff) * arrDiscountYear['value'] / 100 
            else:
                nuMoneyDischarge_year += (nuCountDaysoff - nuMaxDaysoff) * arrDiscountYear['value'] 
        
        
        # ko qua 80% luong mac dinh moi thang
        nuSalary_return = nuSalaryMonthly
        if (nuMoneyDischarge_year + nuMoneyDischarge_week)/nuSalaryMonthly > 0.8:
            nuSalary_return = 0.2 * nuSalaryMonthly
        else:
            nuSalary_return = nuSalaryMonthly - nuMoneyDischarge_year - nuMoneyDischarge_week
       
# testing....
        print 'calSalaryMonthly(by Tri)'
        print '+ arrYMD: ' +  str(arrYMD) + str(len(arrYMD)) + '; dFirstDate='+str(dFirstDate.strftime(self.strFormatTime))
        print '+ arrDaysOff: ' +  str(arrDaysOff) 
        print '+ arrDiscountYear: ' +  str(arrDiscountYear) 
        print '+ nuSalaryMonthly: ' +  str(nuSalaryMonthly)  
        print '+ nuCurrentMonth: ' +  str(nuCurrentMonth)   + '; asd: ' + str(nuCurrentMonth == 4)
        print '+ convertDatetimeFromArrayString: ' + str([value['date'].strftime(self.strFormatTime) + '; ' for value in arrDaysOff_datime])
        print '+ dictWeek_Daysoff: ' + str(dictWeek_Daysoff)
        print '+ strTmp' + strTmp
        print '+ dSalaryPerDay: ' + str(dSalaryPerDay)
        print '+ nuMoneyDischarge_week: ' + str(nuMoneyDischarge_week)
        print '+ nuMoneyDischarge_year: ' + str(nuMoneyDischarge_year) + '; nuCountDaysoff:'+ str(nuCountDaysoff)
        print '+ nuSalary_return: ' + str(nuSalary_return)
        return nuSalary_return
    
    def convertDatetimeFromArrayString(self, arrDatetime_string):
        arrDatetime = []
        dictDatetime = {} # check repeated dates.
        for ind, value in enumerate(arrDatetime_string):     
            strDate = value['date']
            arrYMD = strDate.split('/')
            if len(arrYMD) < 3:
                arrYMD = strDate.split('-')
            if len(arrYMD) < 3:
                arrYMD = strDate.split('.')
                
                
            dFirstDate = datetime.strptime(arrYMD[0] + '-' + arrYMD[1] + '-'+ arrYMD[2], "%Y-%m-%d")
            dFirstDate = dFirstDate.replace(tzinfo= get_localzone()) #.. BMT
            item = {'date': dFirstDate, 'right': value['right']}
            
            #check repeated date
            if dictDatetime.has_key(arrYMD[0] + '-' + arrYMD[1] + '-'+ arrYMD[2]) == False:                
                arrDatetime.append(item)
                # update index at arrDatetime of current yy/mm/dd into dictDatetime
                dictDatetime.update({arrYMD[0] + '-' + arrYMD[1] + '-'+ arrYMD[2]: (len(arrDatetime)-1)})
            else:
                index = dictDatetime[arrYMD[0] + '-' + arrYMD[1] + '-'+ arrYMD[2]]
                # update at the index of current yy/mm/dd 
                arrDatetime[index] = item # the new item (lastest repeated item)
                
                
        print 'convertDatetimeFromArrayString=>dictDatetime' + str(dictDatetime)
        return arrDatetime
    
    
    def findOutDaysoffGroupByWeek(self, dFirstAccountingDate, arrDayoffs, nuMonth = 0):
        dictWeek_Daysoff = {}
#         dictWeek_Daysoff[1] = datetime.now(get_localzone()).strftime(self.strFormatTime)
        iDaysLeftOfFirstAccountingWeek = 6 - dFirstAccountingDate.weekday() + 1
        
        for ind,value in enumerate(arrDayoffs):
            bContinue = True
            if (nuMonth != 0) & (nuMonth != value['date'].month):
                bContinue = False
            if bContinue == True:
                dDelta = value['date'] - dFirstAccountingDate    
                iDays = dDelta.days 
                if iDays - iDaysLeftOfFirstAccountingWeek < 0: # 1st week
                    if 1  in dictWeek_Daysoff:
                        dictWeek_Daysoff[1].append(value)
                    else:
                        dictWeek_Daysoff[1] = [value]
                else:  # from 2nd week go on...
                    iWeek = (iDays - iDaysLeftOfFirstAccountingWeek) / 7 + 2
                    if iWeek  in dictWeek_Daysoff:
                        dictWeek_Daysoff[iWeek].append(value)
                    else:
                        dictWeek_Daysoff[iWeek] = [value]
        return dictWeek_Daysoff
    
    def getAccountMoveLines(self, cr, uid, strInvoiceNumber, context):
        
        print 'getAccountInvoiceMove:...'
        arrInvIDs = self.pool.get('account.invoice').search(cr, uid, [('number', '=', strInvoiceNumber)], order='id DESC')
        strID = 0
        strMoveID = 0
        arrMoveLineIDs = []
        if len(arrInvIDs) > 0:
            strID = arrInvIDs[0]
#             cr.execute('select * from account_move where ')
#             get move_id
            strMoveID = self.pool.get('account.invoice').browse(cr, uid, strID).move_id.id
#             get line of the move_id
            arrMoveLineIDs = self.pool.get('account.move.line').search(cr, uid, [('move_id', '=', strMoveID)], order='id DESC')
            
#             get line of the move_id - another way...
            strQueries = "select * from account_move_line where move_id = " + str(strMoveID)
            cr.execute(strQueries)
            print cr.fetchall()
            
        
        print '+arrInvIDs: ' + str(arrInvIDs)
        print '+strID: ' + str(strID)
        print '+strMoveID: ' + str(strMoveID)
        print '+strMoveID: ' + str(arrMoveLineIDs)
        
        return arrMoveLineIDs
    
    def calAverageSalaryPerday(self, nuSalaryPermonth, nuCurrentYear, nuCurrentMonth):
        nuSalary_re = 0
        
        setMonthRange = monthrange(nuCurrentYear, nuCurrentMonth)
        nuMaxDay = list(setMonthRange)[1]
        
#         for i in xrange(dStart, dStop+1, dStep): 

        dStart = 1
        dStop = nuMaxDay
        dStep = 1
        dDate = datetime.now()
#         dFirstDate = datetime.strptime(arrYMD[0] + '-' + arrYMD[1] + '-'+ arrYMD[2], "%Y-%m-%d")
        arrTemp = []
        arrWeekends = [5, 6] #0: Monday .... 5: Saturday 6: Sunday
        nuCountWorkingDays = 0
        for i in xrange(dStart, dStop + 1, dStep):
            dDate = datetime.strptime(str(nuCurrentYear) +'-'+ str(nuCurrentMonth) +'-'+ str(i), '%Y-%m-%d')
            dDate = dDate.replace(tzinfo= get_localzone()) #.. BMT
            if arrWeekends.__contains__(dDate.weekday()) == False:
                nuCountWorkingDays += 1
                arrTemp.append(str(nuCurrentYear) +'-'+ str(nuCurrentMonth) +'-'+ str(i))
            
        
        nuSalary_re = nuSalaryPermonth / nuCountWorkingDays
        print 'calAverageSalaryPerday..' + str(nuSalary_re)
#         print '+ nuCountWorkingDays: '+str(nuCountWorkingDays)
#         print '+ arrTemp=> len: '+str(len(arrTemp))
        return nuSalary_re
crea8s_training1_demo_class()





